﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class DocumentTypeController : BaseController
    {
        /// <summary>
        /// Lấy toàn bộ loại hồ sơ từ csdl
        /// </summary>
        /// <returns>json</returns>
        [HttpGet]
        [ActionName("get_all")]
        public JsonResult GetAll()
        {
            try
            {
                var items = unitOfWork.DocumentTypeRepository.Get().Select(o => new DocTypeModel(o)).ToList();
                return Json(
                    new JsonResponse() { Status = true, Result = items },
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                //throw;
            }
        }

        /// <summary>
        /// Thêm mới một loại công văn
        /// </summary>
        /// <param name="docType"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("add_doctype")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddDocType(DocTypeModel docType)
        {
            try
            {
                List<ValidationResult> outError;
                if (docType.IsValid(out outError))
                {
                    var dbDocType = new DocumentType()
                                        {
                                            Id = docType.Id,
                                            BookId = docType.IsCommon == true ? null : (docType.BookId == 0 ? null : docType.BookId),
                                            Description = docType.Description,
                                            IsActive = docType.IsActive,
                                            IsCommon = docType.IsCommon,
                                            Name = docType.Name
                                        };
                    dbDocType.CreatedAt = DateTime.Now;
                    dbDocType.UpdatedAt = DateTime.Now;
                    unitOfWork.DocumentTypeRepository.Insert(dbDocType);
                    return Json(SimplyResponse.ResposeWithId(dbDocType.Id));
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });

                }
            }
            catch (DbEntityValidationException dbEx)
            {
                var errors = "";
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errors += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
                return Json(SimplyResponse.Response500(errors));
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        /// <summary>
        /// Cập nhập loại công văn
        /// </summary>
        /// <param name="docType"></param>
        /// <param name="modified"> </param>
        /// <returns></returns>
        [HttpPut]
        [ActionName("update_doctype")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateDocType(DocTypeModel docType, string modified = "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (docType.IsValid(out outError))
                {
                    var dbDocType = unitOfWork.DocumentTypeRepository.GetById(docType.Id);
                    if (dbDocType != null)
                    {
                        if (modified.ToUpper().Equals("ISACTIVE"))
                        {

                        }
                        else
                        {
                            dbDocType.Id = docType.Id;
                            dbDocType.Name = docType.Name;
                            dbDocType.Description = docType.Description;
                            dbDocType.IsActive = docType.IsActive;
                            dbDocType.IsCommon = docType.IsCommon;
                            dbDocType.BookId = docType.BookId;
                        }
                        dbDocType.UpdatedAt = DateTime.Now;
                        unitOfWork.DocumentTypeRepository.Update(dbDocType);
                        return Json(SimplyResponse.Response200());
                    }
                    else
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = Resources.Resources.ManageDocTypeNotFound
                        });
                    }
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        /// <summary>
        /// xóa loại công văn
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("delete_doctype")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteDocType(int id)
        {
            try
            {
                unitOfWork.DocumentTypeRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
            }
        }
    }
}
